using System.Reflection;
using Ellwood.Manage.Common.Core.Basis.Mapper.DTO;
using Ellwood.Manage.Common.Core.Basis.ValidateRules;
using Ellwood.Manage.Common.Core.result;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Ellwood.Manage.MentApi.Utility.Filters;

/// <summary>
/// 自定义验证参数的ActionFilter
/// </summary>
public class CustomAsyncValidateParaActionFilterAttribute: Attribute,IAsyncActionFilter
{
    
    /// <summary>
    /// 参数校验
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // 验证业务逻辑
        List<object?> parameterList = context.ActionArguments
            .Where(p => p.Value is BaseDto && p.Value is not null)
            .Select(c => c.Value).ToList();

        List<(bool, string?)> messageList = new List<(bool, string?)>();
        
        foreach (var parameter in parameterList)
        {
            // 实体验证参数实现 --通过特性
            foreach (var prop in parameter.GetType().GetProperties()
                         .Where(p=>p.IsDefined(typeof(BaseAbstractAttribute),true)))
            {
                    BaseAbstractAttribute? attribute = prop.GetCustomAttribute<BaseAbstractAttribute>();
                    messageList.Add(attribute.DoValidate(prop.GetValue(parameter)));
            }
        }
        
        if (messageList.Any(c=>c.Item1==false))
        {
            context.Result = new JsonResult(new ApiDataResult<string>()
            {
                Success = false,
                Message = string.Join(",", messageList
                    .Where(c => c.Item1 == false)
                    .Select(c => c.Item2))
            });
        }
        else
        {
            await next();
        }

    }
}